package com.wuql.create.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Locale;
import java.util.Map;

/**
 * FreeMarker模版生成文件工具类
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
public class FreeMarkerUtil {

    /**
     *
     * @param data 供模版用的动态数据
     * @param templateName 模版名称
     * @param savePath 生成文件的保存路径 全路径 包含生成文件名
     */
    public static void createFile(Map<String,Object> data,String templateName,String savePath){
        try {
            Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates");
            cfg.setEncoding(Locale.CHINA, "UTF-8");
            Template template = cfg.getTemplate(templateName, "UTF-8");
            StringWriter writer = new StringWriter();
            template.process(data, writer);
            writer.flush();
            String content = writer.toString();
            Path path = Paths.get(savePath);
            Files.createDirectories(path.getParent());
            Files.write(path, content.getBytes());
        }catch (Exception e){
           System.out.println(e.getMessage());
        }
    }
}
